/**
 * 管理员功能相关JavaScript
 */

// 管理员权限检查
function checkAdminPermission() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/api/users/current',
            type: 'GET',
            success: function(user) {
                if (user.userRole === 'ADMIN') {
                    resolve(user);
                } else {
                    reject('您没有管理员权限');
                }
            },
            error: function() {
                reject('请先登录');
            }
        });
    });
}

// 显示加载状态
function showLoading(target, message = '正在加载...') {
    $(target).html(`
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">${message}</p>
        </div>
    `);
}

// 显示错误信息
function showError(target, message) {
    $(target).html(`
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle me-2"></i>
            ${message}
        </div>
    `);
}

// 显示空数据状态
function showEmpty(target, message, iconClass = 'bi-inbox') {
    $(target).html(`
        <div class="text-center py-5">
            <i class="${iconClass}" style="font-size: 4rem; color: #dee2e6;"></i>
            <h5 class="text-muted mt-3">${message}</h5>
        </div>
    `);
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    return new Date(dateTimeStr).toLocaleString();
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '';
    return new Date(dateStr).toLocaleDateString();
}

// 格式化价格
function formatPrice(price) {
    return `¥${parseFloat(price || 0).toFixed(2)}`;
}

// 获取状态徽章
function getStatusBadge(status, type = 'ticket') {
    const badges = {
        ticket: {
            'CONFIRMED': '<span class="badge bg-success">已确认</span>',
            'PENDING': '<span class="badge bg-warning">待确认</span>',
            'CANCELLED': '<span class="badge bg-danger">已取消</span>'
        },
        user: {
            'ACTIVE': '<span class="badge bg-success">正常</span>',
            'INACTIVE': '<span class="badge bg-danger">禁用</span>',
            'PENDING': '<span class="badge bg-warning">待激活</span>'
        },
        schedule: {
            'ACTIVE': '<span class="badge bg-success">正常</span>',
            'CANCELLED': '<span class="badge bg-danger">已取消</span>',
            'DELAYED': '<span class="badge bg-warning">延误</span>'
        }
    };
    
    return badges[type][status] || `<span class="badge bg-secondary">${status}</span>`;
}

// 确认对话框
function confirmAction(message, callback, title = '确认操作') {
    if (confirm(`${title}\n\n${message}\n\n确定要继续吗？`)) {
        callback();
    }
}

// 成功提示
function showSuccess(message, duration = 3000) {
    const alertId = 'success-alert-' + Date.now();
    const alertHtml = `
        <div id="${alertId}" class="alert alert-success alert-dismissible fade show position-fixed" 
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
            <i class="bi bi-check-circle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(alertHtml);
    
    setTimeout(() => {
        $(`#${alertId}`).fadeOut(() => {
            $(`#${alertId}`).remove();
        });
    }, duration);
}

// 错误提示
function showErrorMessage(message, duration = 5000) {
    const alertId = 'error-alert-' + Date.now();
    const alertHtml = `
        <div id="${alertId}" class="alert alert-danger alert-dismissible fade show position-fixed" 
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
            <i class="bi bi-exclamation-triangle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(alertHtml);
    
    setTimeout(() => {
        $(`#${alertId}`).fadeOut(() => {
            $(`#${alertId}`).remove();
        });
    }, duration);
}

// 数据表格渲染器
class DataTableRenderer {
    constructor(tableId, columns, options = {}) {
        this.tableId = tableId;
        this.columns = columns;
        this.options = {
            showActions: true,
            actionButtons: ['edit', 'delete'],
            ...options
        };
    }

    render(data) {
        const table = $(this.tableId);
        
        if (!data || data.length === 0) {
            table.html('<tr><td colspan="' + (this.columns.length + (this.options.showActions ? 1 : 0)) + '" class="text-center text-muted">暂无数据</td></tr>');
            return;
        }

        let html = '';
        data.forEach((item, index) => {
            html += '<tr>';
            
            this.columns.forEach(column => {
                let value = this.getCellValue(item, column);
                html += `<td>${value}</td>`;
            });

            if (this.options.showActions) {
                html += `<td>${this.renderActions(item, index)}</td>`;
            }

            html += '</tr>';
        });

        table.html(html);
        this.bindEvents();
    }

    getCellValue(item, column) {
        let value = item[column.field];
        
        if (column.formatter) {
            return column.formatter(value, item);
        }
        
        return value || '';
    }

    renderActions(item, index) {
        let buttons = '';
        
        this.options.actionButtons.forEach(action => {
            switch(action) {
                case 'edit':
                    buttons += `<button class="btn btn-sm btn-outline-primary me-1 edit-btn" data-id="${item.id}" data-index="${index}">
                        <i class="bi bi-pencil"></i>
                    </button>`;
                    break;
                case 'delete':
                    buttons += `<button class="btn btn-sm btn-outline-danger delete-btn" data-id="${item.id}" data-index="${index}">
                        <i class="bi bi-trash"></i>
                    </button>`;
                    break;
                case 'view':
                    buttons += `<button class="btn btn-sm btn-outline-info me-1 view-btn" data-id="${item.id}" data-index="${index}">
                        <i class="bi bi-eye"></i>
                    </button>`;
                    break;
            }
        });
        
        return `<div class="btn-group">${buttons}</div>`;
    }

    bindEvents() {
        // 编辑事件
        $('.edit-btn').off('click').on('click', (e) => {
            const id = $(e.currentTarget).data('id');
            const index = $(e.currentTarget).data('index');
            if (this.options.onEdit) {
                this.options.onEdit(id, index);
            }
        });

        // 删除事件
        $('.delete-btn').off('click').on('click', (e) => {
            const id = $(e.currentTarget).data('id');
            const index = $(e.currentTarget).data('index');
            if (this.options.onDelete) {
                confirmAction('此操作不可恢复', () => {
                    this.options.onDelete(id, index);
                }, '确认删除');
            }
        });

        // 查看事件
        $('.view-btn').off('click').on('click', (e) => {
            const id = $(e.currentTarget).data('id');
            const index = $(e.currentTarget).data('index');
            if (this.options.onView) {
                this.options.onView(id, index);
            }
        });
    }
}

// 表单验证器
class FormValidator {
    constructor(formId) {
        this.formId = formId;
        this.form = $(formId);
    }

    validate() {
        const form = this.form[0];
        if (!form.checkValidity()) {
            this.form.addClass('was-validated');
            return false;
        }
        return true;
    }

    getFormData() {
        const formData = {};
        this.form.find('input, select, textarea').each(function() {
            const name = $(this).attr('name');
            const value = $(this).val();
            if (name && value !== undefined) {
                formData[name] = value;
            }
        });
        return formData;
    }

    setFormData(data) {
        Object.keys(data).forEach(key => {
            this.form.find(`[name="${key}"]`).val(data[key]);
        });
    }

    reset() {
        this.form[0].reset();
        this.form.removeClass('was-validated');
    }
}

// 模态框管理器
class ModalManager {
    constructor(modalId) {
        this.modalId = modalId;
        this.modal = $(modalId);
        this.bsModal = new bootstrap.Modal(this.modal[0]);
    }

    show(title, content, footerButtons) {
        if (title) {
            this.modal.find('.modal-title').html(title);
        }
        if (content) {
            this.modal.find('.modal-body').html(content);
        }
        if (footerButtons) {
            this.modal.find('.modal-footer').html(footerButtons);
        }
        this.bsModal.show();
    }

    hide() {
        this.bsModal.hide();
    }

    setSize(size) {
        this.modal.find('.modal-dialog').removeClass('modal-sm modal-lg modal-xl').addClass(`modal-${size}`);
    }
}

// 搜索和分页管理器
class SearchPagination {
    constructor(options) {
        this.options = {
            searchInputId: '#searchInput',
            pageSize: 10,
            currentPage: 1,
            ...options
        };
        this.data = [];
        this.filteredData = [];
    }

    init(data) {
        this.data = data;
        this.filteredData = data;
        this.bindEvents();
        this.render();
    }

    bindEvents() {
        // 搜索事件
        $(this.options.searchInputId).on('input', (e) => {
            const keyword = $(e.target).val().toLowerCase();
            this.search(keyword);
        });
    }

    search(keyword) {
        if (!keyword) {
            this.filteredData = this.data;
        } else {
            this.filteredData = this.data.filter(item => {
                return Object.values(item).some(value => 
                    String(value).toLowerCase().includes(keyword)
                );
            });
        }
        this.currentPage = 1;
        this.render();
    }

    paginate() {
        const start = (this.options.currentPage - 1) * this.options.pageSize;
        const end = start + this.options.pageSize;
        return this.filteredData.slice(start, end);
    }

    render() {
        const pageData = this.paginate();
        if (this.options.onRender) {
            this.options.onRender(pageData);
        }
        this.renderPagination();
    }

    renderPagination() {
        if (!this.options.paginationId) return;

        const totalPages = Math.ceil(this.filteredData.length / this.options.pageSize);
        if (totalPages <= 1) {
            $(this.options.paginationId).html('');
            return;
        }

        let html = '<ul class="pagination justify-content-center">';
        
        // 上一页
        html += `<li class="page-item ${this.options.currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${this.options.currentPage - 1}">上一页</a>
        </li>`;

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === this.options.currentPage) {
                html += `<li class="page-item active"><a class="page-link" href="#">${i}</a></li>`;
            } else if (Math.abs(i - this.options.currentPage) <= 2 || i === 1 || i === totalPages) {
                html += `<li class="page-item"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
            } else if (Math.abs(i - this.options.currentPage) === 3) {
                html += '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
            }
        }

        // 下一页
        html += `<li class="page-item ${this.options.currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${this.options.currentPage + 1}">下一页</a>
        </li>`;

        html += '</ul>';

        $(this.options.paginationId).html(html);

        // 绑定分页事件
        $(this.options.paginationId).find('a[data-page]').on('click', (e) => {
            e.preventDefault();
            const page = parseInt($(e.target).data('page'));
            if (page >= 1 && page <= totalPages) {
                this.options.currentPage = page;
                this.render();
            }
        });
    }
}

// 通用AJAX请求函数
function adminRequest(url, method = 'GET', data = null) {
    return new Promise((resolve, reject) => {
        const options = {
            url: url,
            type: method,
            success: resolve,
            error: (xhr) => {
                const message = xhr.responseText || '请求失败';
                reject(message);
            }
        };

        if (data) {
            options.contentType = 'application/json';
            options.data = JSON.stringify(data);
        }

        $.ajax(options);
    });
}

// 导出数据到CSV
function exportToCSV(data, filename, columns) {
    let csv = '';
    
    // 添加列标题
    csv += columns.map(col => col.title || col.field).join(',') + '\n';
    
    // 添加数据行
    data.forEach(row => {
        const values = columns.map(col => {
            let value = row[col.field] || '';
            // 处理包含逗号的值
            if (String(value).includes(',')) {
                value = `"${value}"`;
            }
            return value;
        });
        csv += values.join(',') + '\n';
    });
    
    // 创建下载链接
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 页面初始化时的通用设置
$(document).ready(function() {
    // 初始化工具提示
    if (typeof bootstrap !== 'undefined') {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }    // 全局退出登录事件
    $(document).on('click', '#logoutBtn', function(e) {
        e.preventDefault();
        confirmAction('确定要退出登录吗？', () => {
            $.ajax({
                url: '/logout',
                type: 'POST',
                success: function() {
                    window.location.href = '/custom-login';
                }
            });
        });
    });
});
